package org.codeart.flyweight.demo1;

import java.util.HashMap;
import java.util.Map;

/**
 * 享元工厂类，作为存储享元对象的享元池，用户获取享元对象时先从享元池中获取
 * 有则返回，没有则创建新的返回给用户，并且在享元池中保存
 */
public class FlyweightFactory {

    // 定义一个Map集合用于存储享元对象，实现享元池
    private final Map<String, FlyWeight> pool = new HashMap<>();

    /**
     * 实现享元对象之间的状态传递
     */
    public FlyweightFactory() {
        // 添加对应的内部状态
        pool.put("A", new ConcreteFlyweight("A"));
        pool.put("B", new ConcreteFlyweight("B"));
        pool.put("C", new ConcreteFlyweight("C"));
    }

    /**
     * 根据内部状态进行查找
     */
    public FlyWeight getFlyWeight(String key) {
        if (pool.containsKey(key)) {
            System.out.println("享元池中存在, 直接复用, key: " + key);
            return pool.get(key);
        } else {
            System.out.println("享元池中不存在, 创建并复用, key: " + key);
            FlyWeight f = new ConcreteFlyweight(key);
            pool.put(key, f);
            return f;
        }
    }
}
